package com.syq.shiro.filter;

import com.syq.dto.DTO;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.shiro.session.SessionException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.LogoutFilter;
import org.springframework.stereotype.Component;

import javax.servlet.ServletContext;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.PrintWriter;

/**
 * 注销filter 在context中去掉当前用户的信息
 */
//@Component("logoutFilter")
public class SystemLogoutFilter extends LogoutFilter {
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        //在这里执行退出系统前需要清空的数据
        Subject subject=getSubject(request,response);
        String redirectUrl= "login";
                //如果注销之后 到页面不同 需要考虑从subject中获取url如果是统一的
                //getRedirectUrl(request,response,subject);
        ServletContext context= request.getServletContext();
        try {
            subject.logout();
            context.removeAttribute("error");
        }catch (SessionException e){
            e.printStackTrace();
        }

        response.setCharacterEncoding("utf-8");
        PrintWriter out = response.getWriter();
        DTO dto = new DTO(302,"注销成功",redirectUrl);
        out.print(new ObjectMapper().writeValueAsString(dto));
        out.flush();
        out.close();

        //issueRedirect(request,response,redirectUrl);
        return false;
    }
}
